//
//  XYComposeTextInputView.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/21.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit

private let TEXT_VIEW_MARGIN:CGFloat = 5

class XYComposeTextInputView: UITextView {
    
    var placeholder:String?{
        didSet{
            placeholderLabel.text = placeholder ?? ""
        }
    }
    
    override var font:UIFont?{
        didSet{
            placeholderLabel.font = font
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        //添加一个label
        addSubview(placeholderLabel)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "inputViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //通知
    @objc private func inputViewDidChange(noti:NSNotification){
        placeholderLabel.hidden = self.hasText()
    }
    
    //加载一个label
    private lazy var placeholderLabel : UILabel = {
    
        let label = UILabel()
        
        label.numberOfLines = 0
        
        label.textColor = UIColor.lightGrayColor()
        
//        label.font = UIFont.systemFontOfSize(12)
        
        return label
    }()
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        placeholderLabel.x = TEXT_VIEW_MARGIN
        placeholderLabel.y = 8
        placeholderLabel.size = (self.placeholder ?? "").size(placeholderLabel.font, constrainedToSize: CGSizeMake(self.width - 2 * TEXT_VIEW_MARGIN, CGFloat(MAXFLOAT)))
    }
    
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

}
